//
//  WDG_ComenFunction.m
//  TTPod
//
//  Created by dllo on 16/3/9.
//  Copyright © 2016年 yyx. All rights reserved.
//

#import "WDGComenFunction.h"
@implementation WDGComenFunction

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
+ (void)updateFrame:(UIView *)view{
    
    CGRect rect=view.frame;
    view.frame=CGRectMake(rect.origin.x*FitWidth, rect.origin.y*FitWidth, rect.size.width*FitWidth, rect.size.height*FitWidth);
}
+ (UILabel *)createNavBarTitleLableWithString:(NSString *)str{
    UILabel *barTitlelabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, SysWidth * 0.6, 44 * FitWidth)];
    barTitlelabel.text=str;
    barTitlelabel.textColor=[UIColor whiteColor];
    return barTitlelabel;
}

+ (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

+ (UIColor *)toGrayWithColor:(UIColor *)color nearRate:(CGFloat)value{
    const CGFloat *colors=CGColorGetComponents(color.CGColor);
   return  [UIColor colorWithRed:colors[0]>0.5?colors[0]-value:colors[0]+value green:colors[1]>0.5?colors[1]-value:colors[1]+value blue:colors[2]>0.5?colors[2]-value:colors[2]+value alpha:1];
}

+ (UIColor*)mostColorWithImage:(UIImage *)image{
    
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(50, 50);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    
    if (data == NULL) return nil;
    
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            
            int offset = 4*(x*y);
            
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            
            NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
            [cls addObject:clr];
            
        }
    }
    CGContextRelease(context);
    
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:([MaxColor[3] intValue]/255.0f)];
}


void ProviderReleaseData (void *info, const void *data, size_t size)

{
    
    free((void*)data);
    
}


+ (UIImage*)imageChangeColor:(UIColor *)newColor image:(UIImage*) image

{
    // 分配内存
    const int imageWidth = image.size.width;
    
    const int imageHeight = image.size.height;
    size_t      bytesPerRow = imageWidth * 4;
    
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    
    // 创建context
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
 
    // 遍历像素
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    const  CGFloat *newColors=CGColorGetComponents(newColor.CGColor);
    for (int i = 0; i < pixelNum; i++, pCurPtr++)
    {
        uint8_t* ptr = (uint8_t*)pCurPtr;
        if ((*pCurPtr & 0xFFFFFF00) == 0xffffff00)    // 将白色变成透明
            
        {
            //uint8_t* ptr = (uint8_t*)pCurPtr;
            
            //ptr[0] = 0;
        }
        else
            
        {
            // 改成下面的代码，会将图片转成想要的颜色
            
            //uint8_t* ptr = (uint8_t*)pCurPtr;
            
            ptr[3] = newColors[2]*255; //0~255
            
            ptr[2] = newColors[1]*255;
            
            ptr[1] = newColors[0]*255;
 
        }
    }

    // 将内存转成image
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
    
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                        
                                        kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                        
                                        NULL, true, kCGRenderingIntentDefault);
    
    CGDataProviderRelease(dataProvider);
    
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    // 释放
    
    CGImageRelease(imageRef);
    
    CGContextRelease(context);
    
    CGColorSpaceRelease(colorSpace);
    
    // free(rgbImageBuf) 创建dataProvider时已提供释放函数，这里不用free

    return resultUIImage;
    
}

+ (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize string:(NSString *)str
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}





- (void)cleanAction
{
    //获取完整路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    NSString *cachePath = [path stringByAppendingPathComponent:@"caches"];
    NSLog(@"%@", cachePath);
    
    NSFileManager *manage = [NSFileManager defaultManager];
    if ([manage fileExistsAtPath:cachePath]) {
        NSArray *fileNameArray = [manage subpathsAtPath:cachePath];
        for (NSString *fileName in fileNameArray) {
            //拼接绝对路径
            NSString *absolutePath = [cachePath stringByAppendingPathComponent:fileName];
            //通过文件管理者删除文件
            [manage removeItemAtPath:absolutePath error:nil];
        }
    }
    
}


- (long long)fileSizeAtPath:(NSString *)path
{
    //创建一个文件管理者
    NSFileManager *manage = [NSFileManager defaultManager];
    if ([manage fileExistsAtPath:path]) {
        return [[manage attributesOfItemAtPath:path error:nil] fileSize];
    }
    return 0;
}


- (float)folderSizeAtPath:(NSString *)path
{
    //创建文件管理者
    NSFileManager *manage = [NSFileManager defaultManager];
    if (![manage fileExistsAtPath:path]) {
        return 0;
    }
    //根据路径获取文件夹里面的元素集合
    //获取集合类型的枚举器
    NSEnumerator *enumrator = [[manage subpathsAtPath:path] objectEnumerator];
    //每次遍历得到的文件名
    NSString *fileName = [NSString string];
    //文件夹大小
    float folderSize = 0;
    while ((fileName = [enumrator nextObject]) != nil) {
        NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:absolutePath];
    }
    
    return folderSize / (1024.0 * 1024.0);
}



@end
